<template>
	<view>
		<cu-custom bgColor="bg-informatic-brown" isBack>
			<block slot="backText">返回</block>
			<block slot="content">申请表</block>
		</cu-custom>
        <lab-Steps :value="io2.allSteps"></lab-Steps>	
	
		<form>
			<view class="cu-bar bg-white solids-bottom">
				<view class="action text-xl">
					<text class="cuIcon-title text-blue text-xl"></text>
					<text class="text-bold text-xl">团队申请创客空间</text>
				</view>
			</view>
			<view class="form1">
				<view class="cu-form-group" v-show="io2.fieldAccess.Owner">
					<view class="title">申请人名称</view>
					<input placeholder="请输入申请人名称" v-model="io2.data.Owner" :disabled="io2.fieldAccess.Owner==='r'||!io2.isMyStep"></input>
				</view>
				<view class="cu-form-group" v-show="io2.fieldAccess.TeamName">
					<view class="title">团队名称</view>
					 <picker :range="teamInfo.teams" range-key="Name" @change="selectTeamName" :disabled="io2.fieldAccess.TeamName ==='r'||!io2.isMyStep">
					 	<view class="content" v-if="isStudent">
					 		{{teamInfo.teamName}}
					 	</view>
						<view class="content" v-else>
							{{io2.data.TeamName}}
						</view>
					 </picker>
				</view>
				<view class="cu-form-group" v-show="io2.fieldAccess.Owner">
					<view class="title">负责人手机号</view>
					<input placeholder="选择团队后此字段自动填充" v-model="teamInfo.team.LeaderMobile" :disabled="true"></input>
				</view>
				<view class="cu-form-group" v-show="io2.fieldAccess.MemberGuids||!isStudent">
					<view class="title">团队成员</view>
					<input placeholder="选择团队后此字段自动填充" v-model="io2.data.MemberGuids" :disabled="true"></input>
					<view v-show="!isStudent">
						<button style="width: 200upx;" size="mini" @click="exportexcel">导出成员表</button>
					</view>
				</view>
				<view class="cu-form-group" v-show="io2.fieldAccess.RoomId">
					<view class="title">房间号</view>
					<picker mode = "multiSelector" :range="[assistInfo2.buildings,assistInfo2.roomTemp]" range-key="Name" @columnchange="bindMultiPickerColumnChange"
	           :value="assistInfo2.roomIndex" :disabled="false">
						<view class="content">
							{{io2.data.RoomName}}
						</view>
					</picker>
				</view>
				<view class="cu-form-group" v-show="io2.fieldAccess.ProjectName">
					<view class="title">项目名称</view>
					<input placeholder="请输入项目名称" v-model="io2.data.ProjectName" :disabled="io2.fieldAccess.ProjectName==='r'||!io2.isMyStep"></input>
				</view>
				<view class="cu-form-group" v-show="io2.fieldAccess.TurtorId&&isStudent">
					<view class="title">指导老师工号</view>
					<input placeholder="请输入工号" @blur="selectTeacher" :disabled="io2.fieldAccess.TurtorId!=='w'||!io2.isMyStep"></input>
				</view>
				<view class="cu-form-group" v-show="io2.fieldAccess.TurtorId&&isStudent">
					<view class="title">指导老师姓名</view>
					<input placeholder="输入工号后此字段自动填充" :value="assistInfo2.guideTeacherName" disabled />
<!-- 					<picker :range="assistInfo2.teachers" range-key="RealName" :disabled="io2.fieldAccess.TurtorId!=='w'||!io2.isMyStep">
						<view class="content">
							{{assistInfo2.guideTeacherName}}
						</view>
					</picker> -->
				</view>
				<view class="cu-form-group" v-show="io2.fieldAccess.TurtorProfessional">
					<view class="title">指导老师职称</view>
					<input placeholder="请输入指导老师职称" v-model="io2.data.TurtorProfessional" :disabled="io2.fieldAccess.TurtorProfessional==='r'||!io2.isMyStep"></input>
				</view>
				<view class="cu-form-group" v-show="io2.fieldAccess.TurtorBelongDepart">
					<view class="title">指导老师学院</view>
					<input placeholder="请输入指导老师学院" v-model="io2.data.TurtorBelongDepart" :disabled="io2.fieldAccess.TurtorBelongDepart==='r'||!io2.isMyStep"></input>
				</view>
				<view class="cu-form-group" v-show="isStudent">
					<view class="title">项目内容</view>
					<view><text>{{fileName}}</text></view>
					<button size="mini" @click="chooseFile">选择文件并上传</button>
				</view>
				<view class="cu-form-group" v-show="!isStudent">
					<view class="title">项目内容</view>
					<view><text>{{fileName}}</text></view>
					<view><button style="width: 270upx;" size='mini' @click="downloadFile">下载文件并打开</button></view>
				</view>
			</view>
			<view class="cu-bar bg-white solids-bottom margin-top" v-show="io2.fieldAccess.TurtorOpinion">
				<view class="action text-xl">
					<text class="cuIcon-title text-blue text-xl"></text>
					<text class="text-bold text-xl">指导老师审核</text>
				</view>
			</view>
			<view class="cu-form-group" v-show="io2.fieldAccess.Turtor&&!isStudent">
				<view class="title">老师姓名</view>
				<input v-model="io2.data.Turtor" :disabled="io2.fieldAccess.TurtorId!=='w'||!io2.isMyStep"></input>
			</view>
			<view class="cu-form-group" v-show="io2.fieldAccess.TurtorOpinion">
				<view class="title">审核意见</view>
				<input v-model="io2.data.TurtorOpinion" :disabled="io2.fieldAccess.TurtorOpinion!=='w'||!io2.isMyStep"></input>
			</view>
			<view class="cu-form-group" v-show="io2.fieldAccess.TurtorTime">
				<view class="title">审核时间</view>
				<input v-model="io2.data.TurtorTime" :disabled="io2.fieldAccess.TurtorTime!=='w'||!io2.isMyStep"></input>
			</view>
			<view class="cu-bar bg-white solids-bottom margin-top" v-show="io2.fieldAccess.AdministratorOpinion">
				<view class="action text-xl">
					<text class="cuIcon-title text-blue text-xl"></text>
					<text class="text-bold text-xl">实验室管理员审核</text>
				</view>
			</view>
			<view class="cu-form-group" v-show="io2.fieldAccess.AdministratorName">
				<view class="title">管理员姓名</view>
				<input v-model="io2.data.AdministratorName" :disabled="io2.fieldAccess.AdministratorName!=='w'||!io2.isMyStep"></input>
			</view>
			<view class="cu-form-group" v-show="io2.fieldAccess.AdministratorOpinion">
				<view class="title">管理员意见</view>
				<input v-model="io2.data.AdministratorOpinion" :disabled="io2.fieldAccess.AdministratorOpinion!=='w'||!io2.isMyStep"></input>
			</view>
			<view class="cu-form-group" v-show="io2.fieldAccess.AdministratorTime">
				<view class="title">审核时间</view>
				<input v-model="io2.data.AdministratorTime" :disabled="io2.fieldAccess.AdministratorTime!=='w'||!io2.isMyStep"></input>
			</view>	
		</form>
		<view class="cu-bar bg-white solids-bottom margin-top">
			<view class="action text-xl">
				<text class="cuIcon-title text-blue text-xl"></text>
				<text class="text-bold text-xl">操作流程</text>
			</view>
			<view class="action" @click="foldUp">
				<text class="text-df">{{displayTimeline?'收起':'展开'}}</text>
				<text class="padding-lr-xs text-bold" :class="displayTimeline?'cuIcon-fold':'cuIcon-unfold'"></text>
			</view>
		</view>
		<labTimeLine :timeline="io2.timelines" v-show="displayTimeline"></labTimeLine>
		<view v-if="io2.isMyStep">
			<button class="flex-sub bg-cyan margin-top" @click="onSubmit()" v-if="io2.submitBtns.length===1">{{io2.submitBtns[0].Text}}</button>
			<view style="height: 180rpx; width: 100%;" v-else>
				<view class="flex-sub cu-list grid cu-bar foot" :class="['col-'+io2.submitBtns.length]">
					<view v-for="(item,index) in io2.submitBtns" class="cu-item" @click="onSubmit(item, 1)" :key="index">
						<view :class="item.Icon"></view>
						<text>{{item.Text}}</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	let app=require("@/config");
	export default {
		onLoad(opt) {
			if(opt.create)
			{
				uni.post("/api/ywck/Applicate", {
				}, msg => {
					if (msg.success) {
						this.io2 = msg;
						if(this.io2.currentStep !== "填写申请表")  this.isStudent=false;
						if (this.io2.intstanceState === 3) {
							for (let index in this.io2.allSteps) {
								if (this.io2.allSteps[index].status === 0) {
									this.io2.allSteps[index - 1].status = 30;
									this.io2.timelines[0].steps[0].State = 4;
									break;
								}
							}
						}
					} else {
						uni.showMessage(msg.msg);
					}
				});
				uni.post("/api/team/GetTeams", {}, msg => {
					if (msg.success) {
						this.teamInfo.teams = msg.data;
					} else {
						uni.showToast({
							icon: 'none',
							title: msg.msg
						})
					}
				});	
				uni.post("/api/roomApp/v1/GetRoomAndTeacher", {}, msg => {
					this.assistInfo2 = { ...this.assistInfo2,
						...msg
					};
				});
			}else {
				uni.getStorage({
					key: 'jmpInfo',
					success: (res) => {
						uni.post("/api/workflow/LoadInstance", { ...res.data,
							detail: true
						}, msg => {
							this.io2 = msg;
							if(this.io2.data.RoomName === '') this.io2.data.RoomName = '请选择房间号';
							if(this.io2.currentStep !== "填写申请表")  this.isStudent=false;
							if (this.io2.intstanceState === 3) {
								for (let index in this.io2.allSteps) {
									if (this.io2.allSteps[index].status === 0) {
										this.io2.allSteps[index - 1].status = 30;
										this.io2.timelines[0].steps[0].State = 4;
										break;
									}
								}
							}
						});
					},
				});	
				uni.post("/api/team/GetTeams", {}, msg => {
					if (msg.success) {
						this.teamInfo.teams = msg.data;
					} else {
						uni.showToast({
							icon: 'none',
							title: msg.msg
						})
					}
				});
				let teamId = this.io2.data.TeamId;
				uni.post("/api/team/GetTeam", {teamId}, msg => {
					if(msg.success) {
						this.teamInfo.team = msg.data;
					} 
				});
				uni.post("/api/roomApp/v1/GetRoomAndTeacher", {}, msg => {
					this.assistInfo2 = { ...this.assistInfo2,
						...msg
					};
					let roomDic = {};
					this.assistInfo2.buildings.forEach(building => {
						let buildingName = building.Name;
						building.Rooms.forEach(room => {
							roomDic[room.ID] = buildingName + '-' + room.RoomCode + '-' + room.Name;
						})
					});
					roomDic['00000000-0000-0000-0000-000000000000'] = '请选择房间号';
					this.roomDic2 = roomDic;
					this.assistInfo2.roomTemp = this.assistInfo2.buildings[0].Rooms;
				});
			};
		},
		methods: {
			getTeam(ID) {
				uni.post("/api/team/GetTeam", {ID}, msg => {
					if(msg.success) {
						this.teamInfo.team = msg.data;
						this.io2.data.TeamId = this.teamInfo.team.ID;
						this.getMembers(this.teamInfo.team.ID)
					} else {
						uni.showToast({
							icon: 'none',
							title: msg.msg
						})
					}
				})
			},
			getMembers(teamId) {
				uni.post("/api/team/GetTeamMembers", {teamId}, msg => {
					if(msg.success) {
						this.teamInfo.members = msg.data;
						this.io2.data.MemberGuids=this.teamInfo.members.map((obj)=>{return obj.RealName}).join(",");
						if(this.io2.data.MemberGuids === '') this.io2.data.MemberGuids='暂无成员';
					} else {
						uni.showToast({
							icon: 'none',
							title: msg.msg
						})
					}
				}) 
			},
			exportexcel() {
				let url = app.domain + "/api/ywck/ExportStudent?id=" + this.teamInfo.team.ID;
				window.open(url);
			},
			async formValidate(ajaxFlag) {
				let errors = [];
				if (this.isStudent && this.io2.data.TeamName === "" && this.io2.currentStep ===
					"填写申请表") {
					errors.push("必须选择团队名称");
				}
				if (this.isStudent && this.io2.data.ProjectName === "" && this.io2.currentStep ===
					"填写申请表") {
					errors.push("必须填写项目名称");
				}
				if (this.isStudent && this.io2.data.TurtorId === "00000000-0000-0000-0000-000000000000" && this.io2.currentStep ===
					"填写申请表") {
					errors.push("必须选择指导老师");
				}
				if (this.isStudent && this.io2.data.TurtorProfessional === "" && this.io2.currentStep ===
					"填写申请表") {
					errors.push("必须填写指导老师职称");
				}
				if (this.isStudent && this.io2.data.TurtorBelongDepart === "" && this.io2.currentStep ===
					"填写申请表") {
					errors.push("必须填写指导老师所属学院");
				}
				if (this.isStudent && this.fileName === "文件名" && this.io2.currentStep ===
					"填写申请表") {
					errors.push("必须上传项目内容文件");
				}
				if (!this.isStudent && this.io2.data.RoomName === "" && this.io2.currentStep ===
					"实验室管理员审核分配") {
					errors.push("必须填写分配的房间号");
				}
				return errors;
			},
			async onSubmit(item,ajaxFlag) {
				if (item) {
					this.io2.data[item.Field] = item.Value + "。" + this.io2.data[item.Field];
				}
				this.io2.shouldUpload.forEach(value => {
					this.upload[value] = this.io2[value] || this.io2.data[value];
				});
                let errors = await this.formValidate(ajaxFlag);
                if (errors.length > 0) {
                    uni.showMessage(errors[0]);
                } else {
                    uni.post("/api/workflow/SubmitInstance", { ...this.upload
                    }, msg => {
                        if (msg.success === true) {
                            uni.showMessage('提交成功', 1, '', 'success');
                        } else {
                            uni.showMessage(msg.msg, 1);
                        }
                    })
                }
			},
			chooseFile() {
				uni.chooseFile({
				    count: 1,
				    extension:['.docx','.doc','pdf'],
				    success: (res) => {
						const that=this;
						that.fileName=res.tempFiles[0].name;
						const file=res.tempFiles[0];
						const tempfilepaths=res.tempFilePaths;
						uni.uploadFile({
							url: app.domain + '/api/cms/UploadFile', 
							filePath: tempfilepaths[0],
							name: 'file',
							header: {
							},
							formData: {
								'file': file,
								'id': that.io2.instanceId,
								'single': false,
								'usage': '附件',
								'deviceKey': app.currentUserGuid,
								'fileName': that.fileName,
								'relateTable':'ActivityApplication'
							},
							success: (red) => {
								uni.showMessage('上传成功');
							}
						});
				    }
				});
			},
			downloadFile() {
				uni.post("/api/cms/GetAttachments",{id:this.io2.instanceId,usage:'附件',relateTable:'ActivityApplication'},
				res => {
					if(res.success){
						this.fileName = res.data[res.data.length-1].DisplayName;
						location.href = app.domain + res.data[res.data.length-1].Download;
					}
				});
			},
	        bindMultiPickerColumnChange(e) {
				this.assistInfo2.roomIndex[e.detail.column] = e.detail.value
				switch (e.detail.column) {
					case 0: //拖动第1列
						this.assistInfo2.roomTemp = this.assistInfo2.buildings[this.assistInfo2.roomIndex[0]].Rooms
						break
					case 1: //拖动第2列
						this.io2.data.RoomName = this.roomDic2[this.assistInfo2.roomTemp[this.assistInfo2.roomIndex[1]].ID]
						break
				}
				this.$forceUpdate()
			},
			selectTeamName(e) {
				let u=this.teamInfo.teams[e.detail.value];
				this.teamInfo.teamName=u.Name;
				this.io2.data.TeamName=u.Name;
				this.getTeam(u.ID);
		    },
			selectTeacher(e) {
				if(e.detail.value === '') return;
				let u=this.assistInfo2.teachers.filter(t => {
					return t.RealName.split('/')[1] == e.detail.value;
				});
				if(!u.length){
					let content = `找不到工号为${e.detail.value}的老师，请确认该教师已在系统中注册。`
					uni.showModal({
						title: '找不到指定老师',
						content
					})
					return;
				}
				this.assistInfo2.guideTeacherName=u[0].RealName.split('/')[0];
				this.io2.data.TurtorId=u[0].ID;
			},
			foldUp() {
				this.displayTimeline = !this.displayTimeline;
			}
		},
		data() {
			return {
				io2: {
					instanceId: '',
					fieldAccess: {},
					data: {},
					submitBtns: [],
					shouldUpload: [],
					allSteps: [],
					isMyStep: false,
					timelines: [],
					intstanceState: ''
				},
				teamInfo: {
					teams: [],
					teamName: '请选择团队',
					team: [],
					members: [],
				},
				assistInfo2: {
					buildings: [],
					rooms: [],
					roomTemp: [],
					roomIndex: [0, 0],
					teachers: [],
					guideTeacherName: '',
				},
				fileName:'文件名',
			    upload: [],
				roomDic2: {},
				isStudent: true,
				displayTimeline: true,
				showPicker: false,
			}
		}	
	}
</script>

<style>
	.form1>view>view {
		flex-basis: 31%;
	}

	form>span>view.cu-form-group>view {
		flex-basis: 31%;
	}
	
	.fileinput{
		background-color:#DDDDDD;
		height: 80upx;
	}
	
	.btn{
		width: 300upx;
		background-color: #DDDDDD;
	}
	
   .txt{
		width: 90upx;
	}

	.projectinfo{
		height:200upx;
	}
</style>

